import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging


DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.ext.webapp import template
from math import sqrt
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from datetime import datetime
from google.appengine.api import images
from models import *
from utilities import *

webapp.template.register_template_library('customfilters')



class ArticleDetail(webapp.RequestHandler):
  def get(self,url):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryarticles = Article.all()
    queryarticles.filter('url = ', url)
    articles = queryarticles.fetch(1)
    images = []
    if len(articles) > 0:
      article = articles[0]
      queryfiles = File.all()
      queryfiles.filter('filekey = ', str(article.key()))
      images = queryfiles.fetch(10)
      querycomments = Comment.all()
      querycomments.filter(' keyreference = ', str(article.key()))
      comments = querycomments.fetch(50)
      queryarticlecategories = ArticleCategory.all()
      categories = queryarticlecategories.fetch(20)
    else:
      article = ""
      images = ""
      comments = ""
      categories = 0

    template_values = {
      'article': article,
      'categories': categories,
      'commenturl': '/blog/' + url,
      'currentpage': 'blog',
      'images': images,
      'comments': comments
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/article.html')
    self.response.out.write(template.render(path, template_values))



  def post(self,url):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryarticles = Article.all()
    queryarticles.filter('url = ', url)
    articles = queryarticles.fetch(1)
    images = []
    if len(articles) > 0:
      article = articles[0]
      if self.request.get('send') != '':
        newcomment = Comment()
        newcomment.author = self.request.get('author')
        newcomment.email = self.request.get('email')
        newcomment.email = self.request.get('email')
        newcomment.message = self.request.get('message')
        newcomment.commenttype = 'articles'
        newcomment.keyreference = str(article.key())
        newcomment.put()
        self.redirect('/blog/' + url)


class Articles(webapp.RequestHandler):
  def get(self):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryarticles = Article.all()
    queryarticles.order('-pub_date')
    articles = queryarticles.fetch(10)
    queryarticlecategories = ArticleCategory.all()
    categories = queryarticlecategories.fetch(20)
    template_values = {
      'articles': articles,
      'categories': categories,
      'currentpage': 'blog',
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/articles.html')
    self.response.out.write(template.render(path, template_values))



class ArticlesByCategory(webapp.RequestHandler):
  def get(self,categoryurl):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryarticlecategories = ArticleCategory.all()
    queryarticlecategories.filter(' url = ', categoryurl)
    categories = queryarticlecategories.fetch(1)
    category = ''
    if len(categories) > 0:
      category = categories[0]
      queryarticles = Article.all()
      queryarticles.filter(' category = ', category)
      queryarticles.order('-pub_date')
      articles = queryarticles.fetch(10)
      queryarticlecategories = ArticleCategory.all()
      categories = queryarticlecategories.fetch(20)

      template_values = {
        'category': category,
        'articles': articles,
        'currentpage': 'blog',
        'categories': categories
      }
      path = os.path.join(os.path.dirname(__file__), 'templates/articles.html')
      self.response.out.write(template.render(path, template_values))



class ArticleAction(webapp.RequestHandler):
  def get(self,articleid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     article = Article.get(articleid)
     article.delete()
     self.redirect("/admin/articles/")
     return 1
   elif action=='edit':
     article=Article.get(articleid)
     queryfiles = File.all()
     queryfiles.filter('filekey = ', articleid)
     images = queryfiles.fetch(3)
     queryarticlecategories = ArticleCategory.all()
     queryarticlecategories.order('name')
     categories = queryarticlecategories.fetch(500)
     template_values = {
       'article': article,
       'filekey': articleid,
       'images': images,
       'categories': categories,
       'path': "/admin/articles/" + articleid + "/save/",
     }
   elif action=='new':
     queryarticlecategories = ArticleCategory.all()
     queryarticlecategories.order('name')
     categories = queryarticlecategories.fetch(500)
     template_values = {
       'path': "/admin/articles//save/",
       'categories': categories
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/article.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,articleid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if articleid!='':
       article=Article.get(articleid)
     else:
       article = Article()
     if self.request.get("save")!='':
       title = self.request.get("title")
       url = self.request.get("url")
       category = self.request.get("category")
       codenum = self.request.get("codenum")
       body = self.request.get("body")
       error = False
       if error:
         article=Article.get(articleid)
         queryfiles = File.all()
         queryfiles.filter('filekey = ', articleid)
         images = queryfiles.fetch(3)
         queryarticlecategories = ArticleCategory.all()
         queryarticlecategories.order('name')
         categories = queryarticlecategories.fetch(500)
         template_values = {
           'article': article,
           'images': images,
           'categories': categories,
           'path': "/admin/articles/"+articleid+"/save/",
         }
         path = os.path.join(os.path.dirname(__file__), 'admin/article.html')
         self.response.out.write(template.render(path, template_values))
       else:
         article.title = title
         article.url = url
         article.category = ArticleCategory.get(category)
         article.body = body
         article.put()
         queryfiles = File.all()
         queryfiles.filter('filekey = ', codenum)
         files = queryfiles.fetch(10)
         for afile in files:
           afile.filekey=str(article.key())
           afile.status='a'
           afile.put()
           if afile.imagetype=='article':
             article.imagekey = str(afile.key())
             article.put()

         article.put()
         self.redirect("/admin/articles/")



class ArticleCategoryAction(webapp.RequestHandler):
  def get(self,articlecategoryid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     articlecategory=ArticleCategory.get(articlecategoryid)
     articlecategory.delete()
     self.redirect("/admin/articlecategories/", False)
     return 1
   elif action=='edit':
     articlecategory=ArticleCategory.get(articlecategoryid)
     template_values = {
       'articlecategory': articlecategory,
       'filekey': articlecategoryid,
       'path': "/admin/articlecategories/"+articlecategoryid+"/save/",
     }
   elif action=='new':
     template_values = {
       'path': "/admin/articlecategories//save/",
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/articlecategory.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,articlecategoryid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if articlecategoryid!='':
       articlecategory=ArticleCategory.get(articlecategoryid)
     else:
       articlecategory = ArticleCategory()

     if self.request.get("save")!='':
       url = self.request.get("url")
       name = self.request.get("name")
       description = self.request.get("description")

       articlecategory.url = url
       articlecategory.name = name
       articlecategory.description = description
       articlecategory.put()

     self.redirect("/admin/articlecategories/", True)



class ArticleCategoryList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryarticlecategories = ArticleCategory.all()
   queryarticlecategories.order('name')
   articlecategories = queryarticlecategories.fetch(500)
   for category in articlecategories:
     queryarticles = Article.all()
     queryarticles.filter(' category = ', category)
     queryarticles.order('-pub_date')
     category.articlescounter = queryarticles.count(10)
     category.put()


   template_values = {
     'articlecategories': articlecategories
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/articlecategories.html')
   self.response.out.write(template.render(path, template_values))



class ArticleList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryarticles = Article.all()
   queryarticles.order('title')
   articles = queryarticles.fetch(500)
   template_values = {
     'articles': articles
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/articles.html')
   self.response.out.write(template.render(path, template_values))



def real_main():
  application = webapp.WSGIApplication([
                                        ('/blog/', Articles),
                                        ('/blog/edit/articlecategories/', ArticleCategoryList),
                                        ('/blog/edit/articles/', ArticleList),
                                        ('/blog/category/(.*)/', ArticlesByCategory),
                                        ('/blog/(.*)', ArticleDetail),
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)



def profile_main():
 # This is the main function for profiling 
 # We've renamed our original main() above to real_main()
 import cProfile, pstats
 prof = cProfile.Profile()
 prof = prof.runctx("real_main()", globals(), locals())
 print "<pre>"
 stats = pstats.Stats(prof)
 stats.sort_stats("time")  # Or cumulative
 stats.print_stats(80)  # 80 = how many to print
 # The rest is optional.
 # stats.print_callees()
 # stats.print_callers()
 print "</pre>"

if __name__ == "__main__":
  real_main()
